﻿using UnityEngine;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    //左上对齐，自动换行

    [ExecuteInEditMode]
    public class HorLayoutWrapGroup : MonoBehaviour
    {
        public float left, right, top, bottom;
        public Vector2 space;

#if UNITY_EDITOR
        private void Update()
        {
            Refresh();
        }
#endif

        public void Refresh()
        {
            RectTransform trans = transform as RectTransform;
            Vector2 currPos = new Vector2(left, -top);
            float lineHeight = 0;
            for (int i = 0; i < transform.childCount; i++)
            {
                RectTransform child = transform.GetChild(i) as RectTransform;
                Text txt = child.GetComponent<Text>();
                if (txt)
                {
                    child.sizeDelta = new Vector2(txt.preferredWidth, txt.preferredHeight);
                }
                lineHeight = child.rect.height;
                child.anchorMin = new Vector2(0, 1);
                child.anchorMax = new Vector2(0, 1);
                child.pivot = new Vector2(0.5f, 0.5f);
                Vector2 pos;
                pos.x = currPos.x + child.rect.width * 0.5f;
                pos.y = currPos.y - child.rect.height * 0.5f;
                currPos.x = pos.x + child.rect.width * 0.5f + space.x;
                if (currPos.x > trans.rect.width - right)
                {
                    pos.x = left + child.rect.width * 0.5f;
                    currPos.x = pos.x + child.rect.width * 0.5f + space.x;
                    pos.y -= child.rect.height * 0.5f + space.y;
                    currPos.y = pos.y + child.rect.height * 0.5f;
                }
                child.anchoredPosition = pos;

                if (i == transform.childCount - 1)
                {
                    trans.sizeDelta = new Vector2(trans.sizeDelta.x, -(pos.y - child.rect.height * 0.5f) + bottom);
                }
            }
        }
    }
}